package com.cardone.platform.usercenter.controller;

import java.util.List;
import java.util.Map;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cardone.common.dto.PaginationDto;
import com.cardone.context.Constants;
import com.cardone.platform.usercenter.dto.OrgDto;
import com.cardone.platform.usercenter.service.UsercenterService;
import com.cardone.platform.usercenter.validator.OrgValidator;
import com.cardone.platform.usercenter.vo.OrgVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 部门
 * 
 * @author yaoht
 */
@Setter
@Slf4j
@RequestMapping(OrgController.Paths.ROOT)
@Controller
public class OrgController {
	/**
	 * models集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum models {
		/**
		 * 消息
		 */
		message,

		/**
		 * 组织
		 */
		org;
	}

	/**
	 * 路径集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum Paths {
		/**
		 * 部门主界面
		 */
		index,

		/**
		 * 组织编辑视图路径
		 */
		ORGEdit("org/edit"),

		/**
		 * 组织主界面视图路径
		 */
		ORGIndex("org/index"),

		/**
		 * 组织编辑视图路径
		 */
		ORGNew("org/new"),

		/**
		 * 组织查看编辑视图路径
		 */
		ORGView("org/view");

		/**
		 * 部门视图根目录
		 */
		public static final String ROOT = "/platform/usercenter/org/";

		/**
		 * 路径
		 */
		private final String path;

		/**
		 * 构建
		 * 
		 */
		private Paths() {
			this.path = Paths.ROOT + this.name();
		}

		/**
		 * 构建
		 * 
		 * @param path
		 *            路径
		 */
		private Paths(final String path) {
			this.path = Paths.ROOT + path;
		}

		/**
		 * 获取
		 * 
		 * @return 路径
		 */
		public String path() {
			return this.path;
		}
	}

	/**
	 * 组织验证
	 */
	@Qualifier(OrgValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator orgValidator;

	/**
	 * 部门服务
	 */
	@Qualifier(UsercenterService.BEAN_ID)
	@Autowired(required = false)
	private UsercenterService usercenterService;

	/**
	 * 组织：删除
	 * 
	 * @param orgVo
	 *            组织视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "org/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> orgDelete(final OrgVo orgVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usercenterService.getOrgService().deleteOrgByIds(orgVo.getOrg());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (OrgController.log.isDebugEnabled()) {
				OrgController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 组织：编辑
	 * 
	 * @param orgVo
	 *            组织视图对象
	 * @param model
	 *            上下文映射
	 * @return 组织编辑视图路径
	 */
	@RequestMapping(value = { "org/edit.html" }, method = RequestMethod.GET)
	public String orgEdit(final OrgVo orgVo, final Model model) {
		final OrgDto org = this.usercenterService.getOrgService().findOrgById(orgVo.getOrg());

		model.addAttribute(OrgController.models.org.name(), org);

		return OrgController.Paths.ORGEdit.path();
	}

	/**
	 * 组织：主界面
	 * 
	 * @return 组织主界面视图路径
	 */
	@RequestMapping(value = { "org/index.html" })
	public String orgIndex() {
		return OrgController.Paths.ORGIndex.path();
	}

	/**
	 * 组织：主界面分页查询
	 * 
	 * @param orgVo
	 *            组织视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "org/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> orgIndexPagination(final OrgVo orgVo) {
		final PaginationDto<OrgDto> orgPagination = this.usercenterService.getOrgService().paginationOrgByCode(orgVo.getOrg());

		final Map<String, Object> orgPaginationMap = Maps.newHashMap();

		orgPaginationMap.put(Constants.total.stringValue(), orgPagination.getTotalSize());
		orgPaginationMap.put(Constants.rows.stringValue(), orgPagination.getDataList());

		return orgPaginationMap;
	}

	/**
	 * 组织：新增
	 * 
	 * @param orgVo
	 *            组织视图对象
	 * @param model
	 *            上下文映射
	 * @return 组织编辑视图路径
	 */
	@RequestMapping(value = { "org/new.html" }, method = RequestMethod.GET)
	public String orgNew(final OrgVo orgVo, final Model model) {
		model.addAttribute(OrgController.models.org.name(), orgVo.getOrg());

		return OrgController.Paths.ORGNew.path();
	}

	/**
	 * 组织：保存
	 * 
	 * @param orgVo
	 *            组织视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "org/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String orgSave(final OrgVo orgVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.orgValidator.validate(orgVo.getOrg(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.usercenterService.getOrgService().saveOrgByIdOrCode(orgVo.getOrg());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (OrgController.log.isDebugEnabled()) {
				OrgController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 组织：更新
	 * 
	 * @param orgVo
	 *            组织视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "org/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> orgUpdate(final OrgVo orgVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usercenterService.getOrgService().updateOrgByIds(orgVo.getOrg());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (OrgController.log.isDebugEnabled()) {
				OrgController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 组织：验证
	 * 
	 * @param orgVo
	 *            组织视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "org/validationByCode.json" })
	@ResponseBody
	public Boolean orgValidationByCode(final OrgVo orgVo) {
		try {
			final int count = this.usercenterService.getOrgService().readOrgByCodeNqId(orgVo.getOrg());

			return (count < 1);
		} catch (final Exception e) {
			if (OrgController.log.isDebugEnabled()) {
				OrgController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 组织：查看
	 * 
	 * @param orgVo
	 *            组织视图对象
	 * @param model
	 *            上下文映射
	 * @return 组织查看编辑视图路径
	 */
	@RequestMapping(value = { "org/view.html" }, method = RequestMethod.GET)
	public String orgView(final OrgVo orgVo, final Model model) {
		final OrgDto org = this.usercenterService.getOrgService().findOrgById(orgVo.getOrg());

		model.addAttribute(OrgController.models.org.name(), org);

		return OrgController.Paths.ORGView.path();
	}
}
